package com.ruoyi.system.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.Compute_detail_sum;
import com.ruoyi.system.domain.vo.ProjectVO;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IProjectService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 竞标项目Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-03
 */
@Service
public class ProjectServiceImpl implements IProjectService {
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private ComputeMapper computeMapper;
    @Resource
    private CateMapper cateMapper;
    @Resource
    private ComputeDetailMapper computeDetailMapper;
    @Resource
    private ProjectDetailMapper projectDetailMapper;
    @Resource
    private TypeMapper typeMapper;
    @Resource
    private SpecMapper specMapper;
    @Resource
    private BrandMapper brandMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SettingMapper settingMapper;

    @Resource
    private ProjectCheckMapper projectCheckMapper;
    @Resource
    private ProjectCheckDetailMapper projectCheckDetailMapper;

    private final NotificationService notificationService;

    public ProjectServiceImpl(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    @PostConstruct
    public void init() {
        List<Project> projects = new ArrayList<>();
        Project project = new Project();
        project.getParams().put("searchTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
        project.setStatus(0);
        List<Project> projects_0 = projectMapper.selectProjectList(project);
        project.setStatus(1);
        List<Project> projects_1 = projectMapper.selectProjectList(project);
        if (projects_0 != null && !projects_0.isEmpty()) {
            projects.addAll(projects_0);
        }
        if (projects_1 != null && !projects_1.isEmpty()) {
            projects.addAll(projects_1);
        }

        projects.forEach(item -> {
            if (item.getEndTime().getTime() > System.currentTimeMillis()) {
                LocalDateTime notificationTime = LocalDateTime.parse(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", item.getEndTime()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                notificationService.scheduleNotification(notificationTime, item.getId());
            }
        });

    }

    /**
     * 查询竞标项目
     *
     * @param id 竞标项目主键
     * @return 竞标项目
     */
    @Override
    public ProjectVO selectProjectById(Long id) {
        ProjectVO projectVO = new ProjectVO();
        Project project = projectMapper.selectProjectById(id);
        formatProject(project);

        BeanUtils.copyProperties(project, projectVO);

        //查询竞标项目详情
        List<ProjectDetail> detailList = projectDetailMapper.selectProjectDetailList(new ProjectDetail() {{
            setProjectId(id);
        }});

        projectVO.setDetails(detailList);

        return projectVO;
    }

    /**
     * 查询竞标项目列表
     *
     * @param project 竞标项目
     * @return 竞标项目
     */
    @Override
    public List<Project> selectProjectList(Project project) {

        if (project.getStatus() != null) {
            project.getParams().put("searchTime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
        }

        if (project.getParams().get("deptId") != null) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(String.valueOf(project.getParams().get("deptId"))));
            /*
             * 公司查询竞标项目，根据公司的所属类目查询类目下所有竞标项目
             * */
            if (sysDept.getType() != null && sysDept.getType() == 0) {
                List<Integer> cateIds = Arrays.stream(sysDept.getCate().split(",")).map(Integer::parseInt).collect(Collectors.toList());
                project.getParams().put("cateIds", cateIds);
            }
        }
        List<Project> projects = projectMapper.selectProjectList(project);

        projects.forEach(item -> {
            item.setContent(null);

            formatProject(item);

        });

        return projects;
    }

    /**
     * 格式化
     */
    private void formatProject(Project item) {
        if (item.getCateId() != null) {
            Cate cate = cateMapper.selectCateById(item.getCateId());
            if (cate != null) {
                item.setCateName(cate.getName());
            }
        }
        if (item.getStatus() != 2 && item.getStatus() != 3) {
            if (item.getStartTime().getTime() > System.currentTimeMillis()) {
                //未开始
                item.setStatus(0);
                item.setStatusName("未开始");
            } else {
                //已开始
                item.setStatus(1);
                item.setStatusName("已开始");
            }
        } else {
            if (item.getStatus() == 2) {
                item.setStatusName("已结束");
            }
            if (item.getStatus() == 3) {
                item.setStatusName("已作废");
            }
        }
    }

    /**
     * 新增竞标项目
     *
     * @param project 竞标项目
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProject(Project project) {
        project.setCreateTime(DateUtils.getNowDate());

        //需要compute计算表id
//        if (project.getParams().get("computeIds") == null) {
//            throw new ServiceException("未选择数据");
//        }
        //采购清单
        if (project.getParams().get("details") == null) {
            throw new ServiceException("未选择采购信息");
        }

        Cate cate = cateMapper.selectCateById(project.getCateId());
        if (cate == null) {
            throw new ServiceException("未选择行业类目");
        }

        List<Compute> computeList = JSON.parseArray(JSON.toJSONString(project.getParams().get("details")), Compute.class);

        if (project.getTitle() == null || "".equals(project.getTitle())) {
            String title = "恒清食品科技有限公司";

            if (!computeList.isEmpty()) {
                Compute compute = computeMapper.selectComputeById(computeList.get(0).getId());
                title += compute.getWeekStart() + "-" + compute.getWeekEnd();
                title += cate.getName() + "报价";
            }

            project.setTitle(title);
        }
        project.setContent(new String(Base64.decode(project.getContent())));

        //查询程序设置
        List<Setting> settings = settingMapper.selectSettingList(new Setting());
        if (settings == null || settings.isEmpty()) {
            throw new ServiceException("未查询到程序设置");
        }
        Setting setting = settings.get(0);
        long time = project.getStartTime().getTime();
        project.setEndTime(new Date(time + setting.getEndTime() * 60L * 1000L));

        int i = projectMapper.insertProject(project);
        //同步新增竞标项目检查表
        ProjectCheck projectCheck = new ProjectCheck();
        BeanUtils.copyProperties(project, projectCheck);
        projectCheck.setProjectId(project.getId());
        projectCheck.setId(null);
        projectCheckMapper.insertProjectCheck(projectCheck);


        List<ProjectDetail> details = new ArrayList<>(10);
        computeList.forEach(item -> {
            ProjectDetail projectDetail = new ProjectDetail();
            projectDetail.setProjectId(project.getId());
            projectDetail.setComputeId(item.getId());
            projectDetail.setName(typeMapper.selectTypeById(item.getTypeId()).getName());
            projectDetail.setSpec(specMapper.selectSpecById(item.getSpecId()).getName());
            projectDetail.setBrand(brandMapper.selectBrandById(item.getBrandId()).getName());
            projectDetail.setNum(item.getAllNum());
            projectDetail.setTypeId(item.getTypeId());
            projectDetail.setSpecId(item.getSpecId());
            projectDetail.setBrandId(item.getBrandId());
            projectDetail.setPrice(item.getPrice());
            details.add(projectDetail);
        });
        Map<String, Object> detailsMap_add = new HashMap<>();
        detailsMap_add.put("details", details);
        projectDetailMapper.insertProjectDetailBatch(detailsMap_add);

        //同步新增竞标项目检查详情表
        details.forEach(item -> {
            item.setProjectId(projectCheck.getId());
        });
        detailsMap_add.put("details", details);
        projectCheckDetailMapper.insertProjectCheckDetailBatch(detailsMap_add);

        List<Long> computeIds = computeList.stream().map(Compute::getId).collect(Collectors.toList());
        //将发起竞标得算量都标记为已发起
        computeMapper.updateComputeStatus(new HashMap<String, Object>() {{
            put("computeIds", computeIds);
            put("status", 1);
        }});
        LocalDateTime notificationTime = LocalDateTime.parse(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", project.getEndTime()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        notificationService.scheduleNotification(notificationTime, project.getId());


        /*List<ProjectDetail> detailList = new ArrayList<>(10);
        computeIds.forEach(item -> {
            List<Compute_detail_sum> detailSums = computeDetailMapper.detailSum(new HashMap<String, Object>() {{
                put("computeId", item);
            }});



        });*/


        return i;
    }

    /**
     * 修改竞标项目
     *
     * @param project 竞标项目
     * @return 结果
     */
    @Override
    public int updateProject(Project project) {
        project.setUpdateTime(DateUtils.getNowDate());
        return projectMapper.updateProject(project);
    }

    /**
     * 批量删除竞标项目
     *
     * @param ids 需要删除的竞标项目主键
     * @return 结果
     */
    @Override
    public int deleteProjectByIds(Long[] ids) {
        int i = projectMapper.deleteProjectByIds(ids);
        for (Long id : ids) {
            notificationService.cancelNotification(id);
        }
        return i;
    }

    /**
     * 删除竞标项目信息
     *
     * @param id 竞标项目主键
     * @return 结果
     */
    @Override
    public int deleteProjectById(Long id) {
        return projectMapper.deleteProjectById(id);
    }
}
